package org.itli.jnsocket.Controller;

import org.itli.jnsocket.Util.JWTUtil;
import org.itli.jnsocket.VTO.LoginVTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Result.Result;
import org.itli.jnsocket.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Tag(name = "用户接口")
@RestController
@RequestMapping("/User")
public class UserController {

    private UserService Service;

    JWTUtil jwt = new JWTUtil();

    @Autowired
    public void setService(UserService service) {
        Service = service;
    }

    @PostMapping("/Login")
    @Operation(summary = "用户登录")
    public Result<String> Login(@RequestBody LoginVTO logins) {
        log.info("接收到："+logins);
        String login = Service.Login(logins.getAccouny(), logins.getPassword(),logins.getIp());
        return Result.success(login);
    }

    @PostMapping("/Rigist")
    @Operation(summary = "用户注册")
    public Result<String> Register(@RequestBody LoginVTO rigist){
        log.info(rigist.toString());
        String register = Service.Register(rigist.getAccouny(), rigist.getPassword());
        log.info(register);
        return Result.success(register);
    }

    @GetMapping("/MyInfo")
    @Operation(summary = "获取全部用户信息")
    public Result<String> MyInfo(@RequestHeader("Authorization") String token){
        log.info("通过代理请求到后端！");
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = Service.MyInfo(username);
        log.info(s);
        return Result.success(s);
    }

}
